package com.step.ems.pages.urgent

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.step.ems.Destinations.ID
import com.step.ems.api.ApiService
import com.step.ems.api.UrgentStatus
import com.step.ems.api.res.UrgentDetailRes
import com.step.ems.common.UiState
import com.step.ems.common.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class UrgentDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val apiService: ApiService
) : ViewModel() {
    val id = savedStateHandle.get<Int>(ID) ?: 0

    private val _uiState = MutableStateFlow<UiState>(UiState.Empty)
    val uiState = _uiState.asStateFlow()

    private val _data = MutableStateFlow(UrgentDetailRes())
    val data get() = _data.asStateFlow()

    var faultReason: MutableState<String> = mutableStateOf("")
    var handleMethod = mutableStateOf("")

    init {
        getData()
    }

    private fun getData() {
        launch(
            state = _uiState,
            delayTime = 200,
            onStart = {
                _uiState.value = UiState.Loading()
            }) {
            _data.value = apiService.urgentDetail(id).get()
            _uiState.value = UiState.Success
        }
    }

    fun changeStatus() {
        launch(
            state = _uiState,
            onStart = {
                _uiState.value = UiState.Loading()
            }) {
            val req = _data.value.emergency
            when (req.emergencyStatus) {
                UrgentStatus.Alarmed.value -> {
                    apiService.urgentReceivedAlarm(req).get()
                }

                UrgentStatus.Accept.value -> {
                    apiService.urgentArrived(req).get()
                }

                UrgentStatus.Arrow.value -> {
                    req.causeFailure = faultReason.value
                    req.treatmentMode = handleMethod.value
                    apiService.urgentFinished(req).get()
                }
            }
            _uiState.value = UiState.Success
            getData()
        }
    }
}